package cloud.zhixinglu.www.spring.boot.paho.mqtt.mqtt;


import cloud.zhixinglu.www.spring.boot.paho.mqtt.enums.TopicEnum;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * MQTT消费者配置
 * @author xct
 * @date 2021/7/30 17:06
 */
@Slf4j
@Service
public class MqttConsumerConfig {

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.url}")
    private String hostUrl;

    @Value("${mqtt.qos}")
    private int qos;

    @Value("${mqtt.retained}")
    private boolean retained;

    @Value("${mqtt.connectionTimeout}")
    private Integer connectionTimeout;

    @Value("${mqtt.keepAliveInterval}")
    private Integer keepAliveInterval;

    @Value("${mqtt.consumerPre}")
    private String consumerPre;

    /**
     * 客户端对象
     */
    private MqttClient client;

    @Resource
    private MqttProviderConfig providerConfig;

    /**
     * 在bean初始化后连接到服务器
     *
     * @author xct
     * @date 2021/7/30 16:48
     */
    @PostConstruct
    public void init() {
        String clientId = connect();
        // 存储会话
    }

    /**
     * 客户端连接服务端
     *
     * @author xct
     * @date 2021/7/30 16:01
     */
    public String connect() {
        log.info("MQTT消费者开始链接");
        String clientId = consumerPre + "_" + IdUtil.getSnowflakeNextIdStr();
        log.info("MqttConsumerConfig.connect info, consumer client id: {}", clientId);
        try {
            //创建MQTT客户端对象
            client = new MqttClient(hostUrl, clientId, new MemoryPersistence());
            // MQTT 连接选项
            MqttConnectOptions options = createMqttConnectOptions();
            // 设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill(TopicEnum.WILL_TOPIC.getTopic(),
                    (clientId + "与服务器断开连接").getBytes(),
                    qos,
                    retained);

            // 设置回调
            client.setCallback(new MqttConsumerCallBack());
            // 建立连接
            client.connect(options);

            // 订阅主题
            // 消息等级，和主题数组一一对应，服务端将按照指定等级给订阅了主题的客户端推送消息
            String[] topicList = {
                    "/test/7777",
                    "user/logout/issued",
                    "/user/logout/issued"
            };
            int[] qosList = {2, 2, 2};

            client.subscribe(topicList, qosList);

            return clientId;
        } catch (MqttException e) {
            log.error("mqtt connection failed, error: " + e.getMessage());
            return null;
        }
    }

    /**
     * 创建 MQTT 链接配置
     * @return MqttConnectOptions
     */
    private MqttConnectOptions createMqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        // 是否自动重连
        options.setAutomaticReconnect(true);
        // 重连间隔时间的最大值，默认为 128000 毫秒
        options.setMaxReconnectDelay(128000);
        // 是否清空session，设置为false表示服务器会保留客户端的连接记录（订阅主题，qos），客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
        // 设置为true表示每次连接到服务端都是以新的身份
        options.setCleanSession(true);
        // 设置连接用户名
        options.setUserName(username);
        // 设置连接密码
        options.setPassword(password.toCharArray());
        // 设置超时时间，单位为秒
        options.setConnectionTimeout(connectionTimeout);
        // 设置心跳时间 单位为秒，表示服务器每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
        options.setKeepAliveInterval(keepAliveInterval);
        // 遗嘱消息，当客户端异常断开时发送的消息
        return options;
    }

    /**
     * 断开连接
     *
     * @author xct
     * @date 2021/8/2 09:30
     */
    public void disConnect() {
        try {
            log.debug("MQTT消费者断开连接");
            client.disconnect();
        } catch (MqttException e) {
            log.error("mqtt disconnect failed, error: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 订阅主题
     *
     * @param topic String
     * @param qos   int
     * @date 2021/7/30 17:12
     */
    public void subscribe(String topic, int qos) {
        try {
            client.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("mqtt subscribe failed, error: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
